var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var gameRouter = require('./routes/gameRouter');
var gameManageRouter = require('./routes/gameManage/gameManageRouter');
const JWT = require("./util/JWT")
const fs = require('fs');

var history = require('connect-history-api-fallback');

var app = express();

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');//允许所有的请求源
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');//允许请求的方法
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length');//允许请求携带的头 前端给后端
    res.header("Access-Control-Expose-Headers", 'Authorization,Content-Type');//暴露响应头 后端给前端 Authorization
    next();
});

app.use(history())
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());



console.log("当前目录", __dirname);
app.use(express.static(path.join(__dirname, 'public/')));
app.use('/uploads', express.static(path.join(__dirname, 'public', 'uploads')));



//设置中间件，token过期校验
app.use((req, res, next) => {
    //排除login相关的路由和接口
    if (req.url.includes("login") || req.url.includes("register")) {
        console.log("login相关的路由和接口");
        next()
        return
    }
    const token = req.headers["authorization"]?.split(" ")[1]
    if (token) {
        const payload = JWT.verify(token)
        if (payload) {
            //重新计算token过期时间
            const newToken = JWT.generate({
                _id: payload._id
            }, "1d")
            res.header("Authorization", newToken)
            next()
        } else {
            console.log("token过期");
            res.status(401).send({ errCode: -1, errInfo: "token过期" })
        }
    } else {
        next()
    }
})

app.use('/game', gameRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use((err, req, res, next) => {
  console.error('错误:', err.stack);
  res.status(500).send('服务器内部错误: ' + err.message);
});

module.exports = app;
